/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-use-before-define */
import CustomerTable from "@/components/CustomerTable";
import DictTag from "@/components/DictTag";
import ExportModal from "@/components/ExportModal";
// import position from "@/services/api/organize/post";
import downLoad from "@/utils/download";
import {
	CloudDownloadOutlined,
	CloudServerOutlined,
	DeleteOutlined,
	ExclamationCircleFilled,
	ExportOutlined,
	PlusOutlined
} from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns, ProTable } from "@ant-design/pro-components";
// import { FormattedMessage, useAccess, useIntl } from "@umijs/max";
import type { FormInstance, MenuProps } from "antd";
import { Button, Divider, Dropdown, Input, Modal, Popconfirm, Space, Typography, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import PostForm, { PostFormData } from "./components/postForm";
import { getDict } from "@/services/api/module/system/dict";
import { getPageList, save, update, remove } from "@/services/api/module/system/post";
import FilterDrawer from "@/components/FilterDrawer";
import ImportExportDropdown from "@/components/ImportExportDropdown";
import { createTableColumns, pagination, proTableCardProps } from "./constants";
const { confirm } = Modal;
import { dict } from "@/utils/DictionaryCacheManager";
const PositionTableList: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [modalVisible, setModalVisible] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentRowId, setCurrentRowId] = useState<number | undefined>(undefined);
	const [selectedRows, setSelectedRows] = useState<any>([]);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [exportOpen, setExportOpen] = useState<boolean>(false);
	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	useEffect(() => {
		dict.getDict("sys_base_status").then(data => {
			setStatusOptions(data);
		});
	}, []);
	// 删除
	const handleRemove = async (ids: number | Array<number>) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};
	//列操作回调函数
	const handleColumnEditor = (record: API.Setting.PostVo) => {
		setCurrentRowId(record.id);
		setModalVisible(true);
	};
	//列操作回调函数
	const handleColumnRemove = (record: API.Setting.PostVo) => {
		handleRemove(record?.id);
	};
	// 删除警告提示
	const showRemoveConfirm = (ids: Array<number>, names: Array<string>) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: `确认删除职位名称为：${names} 的职位吗?`,
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};
	// 列表字段
	const columns: ProColumns<API.Setting.PostVo>[] = createTableColumns(statusOptions, handleColumnEditor, handleColumnRemove);
	// 保存
	const handleSave = async (values: PostFormData) => {
		return new Promise((resolve, reject) => {
			save({ ...values } as PostFormData)
				.then((res: any) => {
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 編輯
	const handleUpdate = async (values: PostFormData) => {
		return new Promise((resolve, reject) => {
			update({ ...values } as PostFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setModalVisible(false);
		setCurrentRowId(undefined);
		if (actionRef.current) {
			actionRef.current.reload();
		}
	};
	// 请求列表数据
	const tableDataRequest = async (params: any) => {
		return await getPageList({ ...searchFormValue, ...searchValue }).then(res => {
			return res;
		});
	};

	const handleExport = async (values: any) => {
		const downLoadParams = {
			...values,
			...formTableRef?.current?.getFieldsValue(),
			current: actionRef?.current?.pageInfo?.current,
			pageSize: actionRef?.current?.pageInfo?.pageSize
		};
		return new Promise<void>((reslove, reject) => {
			downLoad.export("/system/post/export", downLoadParams);
			reslove();
		})
			.then(() => {
				setExportOpen(false);
				return Promise.resolve();
			})
			.catch(() => {
				return Promise.reject();
			});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			name: value
		});
		actionRef.current?.reload();
	};
	//操作栏
	const handleCreateForm = () => {
		setModalVisible(true);
		setCurrentRowId(undefined);
	};
	//操作栏
	const handleBatchRemove = () => {
		if (selectedRows.length <= 0) {
			message.warning("请选择一条或多条数据");
			return;
		}
		showRemoveConfirm(
			Array.from(selectedRows, ({ id }) => id),
			Array.from(selectedRows, ({ name }) => name)
		);
	};

	return (
		<>
			<CustomerTable<API.Setting.PostVo>
				actionRef={actionRef}
				cardProps={proTableCardProps}
				formRef={formTableRef}
				rowKey="id"
				search={false}
				key="postTable"
				tableStyle={{ minHeight: "calc(100vh - 205px)" }}
				toolbar={{
					search: (
						<Space>
							<Input.Search placeholder="通过职位名称搜索" allowClear style={{ width: 280 }} onSearch={handleOnSearch} />
							<FilterDrawer
								columns={columns}
								tableActionRef={actionRef}
								onReset={() => {
									setSearchFormValue(undefined);
									actionRef?.current?.reload();
								}}
								onSubmit={(values: any) => {
									setSearchFormValue(values);
									actionRef?.current?.reload();
								}}
							/>
						</Space>
					)
				}}
				pagination={pagination}
				request={tableDataRequest}
				tableAlertRender={false}
				// @ts-ignore
				toolBarRender={() => {
					return (
						<>
							<Button type="primary" key="add" onClick={handleCreateForm}>
								<PlusOutlined />
								创建职位
							</Button>
							<ImportExportDropdown columns={columns} onExport={handleExport} />
							{selectedRows.length > 0 && (
								<Button type="primary" danger key="removes" onClick={handleBatchRemove}>
									<DeleteOutlined />
									批量删除
								</Button>
							)}
						</>
					);
				}}
				columns={columns}
				rowSelection={{
					onChange: (_, selectedRows) => {
						setSelectedRows(selectedRows);
					}
				}}
			/>
			<PostForm
				onSubmit={async (values: PostFormData) => {
					return values.id ? await handleUpdate(values) : await handleSave(values);
				}}
				id={currentRowId}
				onCancel={() => {
					setModalVisible(false);
					setCurrentRowId(undefined);
				}}
				open={modalVisible}
				statusOptions={statusOptions}
			/>
		</>
	);
};

export default PositionTableList;
